/* eslint-disable no-undef */
import axios from 'axios'

// 给axios设置一些默认行为
switch (process.env.NODE_ENV) {
    case 'production':
        axios.defaults.baseURL = 'http://localhost:5000';
        break;
    case 'development':
        axios.defaults.baseURL = 'http://localhost:5000';
        break;
    default:
        break;
}

axios.interceptors.request.use(config => {
    const token = localStorage.getItem("token")
    config.headers.token = `Bearer ${token}`

    return config;
}, error => {
    return Promise.reject(error);
});

axios.interceptors.response.use(response => {

    if (response?.data?.data) {
        const { token } = response.data.data;
        token && localStorage.setItem("token", token);
    }

    return response;
}, error => {
    if (error?.response) {
        const { status } = error.response;
        if (status === 401) {
            localStorage.removeItem('token');
            window.location.href = '/login';
        }
    }

    return Promise.reject(error);
});


export default axios